<?php

namespace app\admin\model;

use app\admin\exception\DuplicateException;
use think\Model;

class Device extends Model
{
    //

    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    protected $type = [
        'expired_time' => 'integer:Y-m-d H:i:s',
    ];

    public function import($codes)
    {
        $data = [];
        foreach ($codes as $key => $value) {
            $data[] = [
                'device_code' => $value,
                'status'      => 1
            ];
        }
        $rows = $this->where('device_code', 'in', array_map(function ($item) {
            return $item['device_code'];
        }, $data))->select();
        if (!empty($rows)) {
            $this->error = '设备编号重复';
            throw new DuplicateException('设备编号重复', array_map(function ($item) {
                return $item['device_code'];
            }, $rows));
        }

        return $this->saveAll($data);
    }

    public function getStatusTxtAttr($value, $data)
    {
        $status = [1 => '空闲', 2 => '分配使用中'];
        return $status[$data['status']];
    }

}
